package yk.YKComics.Test.Plugin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.graphics.Bitmap;
import android.util.Log;

public class PDFHandler
{
	private static String so_file_name = "libYKComicsPDFPlugin.so";
	
	public static native int OpenFile(String FileName);
	public static native void CloseFile();
	
	public static native void MovePage(int PageNum);
	
	public static native int GetTotalPage();
	public static native float GetPageWidth();
	public static native float GetPageHeight();
	
	public static native int DrawPage( Bitmap bitmap, int pageW, int pageH, int patchX, int patchY, int patchW, int patchH );

	public static boolean Process_armeabi( String _install_dir_path, String _app_data_dir_path )
	{
		if ( !ZipExtractFile( _install_dir_path, "lib/armeabi/"+so_file_name, _app_data_dir_path + "/" + so_file_name ) )
			return false;
		
		System.load( _app_data_dir_path + "/" + so_file_name );
		
		return true;
	}

	public static boolean Process_armeabi_v7a( String _install_dir_path, String _app_data_dir_path )
	{
		if ( !ZipExtractFile( _install_dir_path, "lib/armeabi-v7a/"+so_file_name, _app_data_dir_path + "/" + so_file_name ) )
			return false;
		
		System.load( _app_data_dir_path + "/" + so_file_name );
		
		return true;
	}
	
	public static void	LoadLibrary( String _app_data_dir_path )
	{
		System.load( _app_data_dir_path + "/" + so_file_name );
	}
	
	public static boolean ZipExtractFile(String _zip_path, String _src_file_path, String _dest_file_path )
	{
		boolean is_success = false;
		ZipFile zip = null;
		ZipEntry zipen = null;
		
		try
		{
			File DstFileObj = new File(_dest_file_path);
			
			zip = new ZipFile(_zip_path);
			zipen = zip.getEntry(_src_file_path);
			
			if ((!DstFileObj.exists()) || (zipen.getSize() != DstFileObj.length()))
			{
				InputStream is = zip.getInputStream(zipen);
				OutputStream os = new FileOutputStream(DstFileObj);
				
				byte[] buf = new byte[5*1024];
				int n;
				while ((n = is.read(buf)) > 0)
				{
					os.write(buf, 0, n);
				}
				os.close();
				is.close();
				
				is_success = true;
			}
		} 
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		try
		{
			if ( zip != null )
				zip.close();
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
		
		return is_success;
	}

	public static String GetLibraryFileName()
	{
		return so_file_name;
	}
}
